﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Wild2.Models.Exceptions;
using System.Text.RegularExpressions;
using System.Configuration;
using Wild2.Models.Captcha;

namespace Wild2.Controllers
{
    public class SandboxTopicController : Controller
    {
        public ActionResult Index(int id, int p)
        {
            int tid = id;
            if (tid < 0) tid = Wild2.Models.Topic.Topic.GetSandboxTopicIDFromMID(Math.Abs(id));
            if (Wild2.Models.Auth.AuthOnSite.GetUserId().HasValue) Models.Favorites.Favorites.AddFavoriteToSession("Тема из песочницы");
            Wild2.Models.Pages.SandboxTopic.Index page = new Models.Pages.SandboxTopic.Index();
            page.Topic = Wild2.Models.Topic.Topic.GetSandboxTopicInfo(tid);
            page.CountComments = Wild2.Models.Topic.Topic.GetSandboxTopicCountComments(tid);
            page.CurrentPage = p;
            page.LastPage = 1;
            page.ElOnPage = 10;
            if (ConfigurationManager.AppSettings["elonpage"] != null) { page.ElOnPage = Int32.Parse(ConfigurationManager.AppSettings["elonpage"]) * 2; }
            if (page.CountComments % page.ElOnPage == 0) page.LastPage = page.CountComments / page.ElOnPage;
            else { page.LastPage = (int)Math.Truncate((float)page.CountComments / (float)page.ElOnPage) + 1; }
            if (page.CurrentPage > page.LastPage && page.LastPage > 0)
            {
                return RedirectToAction("Index", new { id = id, p = 1 });
            }

            if (Request.QueryString["votes"] != null)
            {
                page.Votes = Wild2.Models.Topic.Topic.GetSandboxVotesList(tid);
            }
            page.Comments = Wild2.Models.Topic.Topic.GetSandboxTopicComments(tid, p);
            return View(page);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(int id, int p, string nick, string message, string captcha)
        {
            int tid = id;
            if (tid < 0) tid = Wild2.Models.Topic.Topic.GetSandboxTopicIDFromMID(Math.Abs(id));

            Wild2.Models.Pages.SandboxTopic.Index page = new Models.Pages.SandboxTopic.Index();
            Int32? UserID = Wild2.Models.Auth.AuthOnSite.GetUserId();
            bool captchaPassed = true;
            if (UserID.HasValue)
            {
                nick = Wild2.Models.Auth.AuthOnSite.GetUserNick();
            }
            else
            {
                if (string.IsNullOrEmpty(nick))
                {
                    nick = Wild2.Models.Auth.AuthOnSite.GetUserNick() ?? "";
                }
                else
                {
                    if (!Wild2.Models.Auth.RegisterOnSite._reg.IsMatch(nick))
                    {
                        HttpContext.Session[Wild2.Models.Constants.SessionConstants.USERNICK] = nick;
                    }
                }
                if(Session[Wild2.Models.Constants.SessionConstants.CAPCHA_PASSED] == null)
                {
                    Captcha c = Session[Wild2.Models.Constants.SessionConstants.CAPCHA + "1"] as Captcha;
                    if (c != null && captcha != c.text)
                    {
                        c = Session[Wild2.Models.Constants.SessionConstants.CAPCHA + "2"] as Captcha;
                        if (c != null && captcha != c.text)
                        {
                            captchaPassed = false;
                        }
                        else
                        {
                            Session[Wild2.Models.Constants.SessionConstants.CAPCHA_PASSED] = true;
                        }
                    }
                    else
                    {
                        Session[Wild2.Models.Constants.SessionConstants.CAPCHA_PASSED] = true;
                    }
                }
            }
            if (!Wild2.Models.Auth.RegisterOnSite._reg.IsMatch(nick) && captchaPassed)
            {
                if (UserID.HasValue) nick = "*" + nick;
                if (Wild2.Models.Text.Helper.GetLastMessage() != message)
                {
                    int result = 0;
                    if (id > 0)
                        try
                        {
                            result = Wild2.Models.Topic.Topic.AddSandboxTopicComment(UserID, nick, tid, message);
                        }
                        catch (TextException e)
                        {
                            page.infoMessage = e.Message;
                        }
                    else
                        try
                        {
                            result = Wild2.Models.Topic.Topic.AddSandboxTopicCommentAnswer(UserID, nick, Math.Abs(id), message);
                        }
                        catch (TextException e)
                        {
                            page.infoMessage = e.Message;
                        }
                    if (result > 0)
                    {
                        Wild2.Models.Text.Helper.SetLastMessage(message);
                        var url = UrlHelper.GenerateUrl(
                            null,
                            "Index",
                            "SandboxTopic",
                            null,
                            null,
                            Math.Abs(id).ToString(),
                            new RouteValueDictionary(new { id = tid }),
                            Url.RouteCollection,
                            Url.RequestContext,
                            false);
                        //return RedirectToAction("Index", new { id = tid });
                        return Redirect(url);
                    }
                }
                else
                {
                    page.infoMessage = "Это сообщение уже отправлено";
                }
            }
            else
            {
                if (captchaPassed) page.infoMessage = "Ник содержит недопустимые символы";
                else page.infoMessage = "Код с картинки введен не правильно";
            }
            page.Topic = Wild2.Models.Topic.Topic.GetSandboxTopicInfo(tid);
            page.Comments = Wild2.Models.Topic.Topic.GetSandboxTopicComments(tid, p);
            if (Request.QueryString["votes"] != null)
            {
                page.Votes = Wild2.Models.Topic.Topic.GetSandboxVotesList(tid);
            }
            return View(page);
        }

        public ActionResult Vote(int topic, int vote, String hash)
        {
            Int32? UserID = Wild2.Models.Auth.AuthOnSite.GetUserId();
            if (UserID.HasValue)
            {
                if (hash == Wild2.Models.Auth.AuthOnSite.GetSessionHash())
                {
                    if (vote < 0) { Wild2.Models.Topic.Topic.VoteSandboxMinus(UserID.Value, topic); }
                    if (vote > 0) { Wild2.Models.Topic.Topic.VoteSandboxPlus(UserID.Value, topic); }
                }
            }
            return RedirectToAction("Index", new { id = topic });
        }
    }
}
